/**
 * grid
 */
define(function(require, exports, module) {
	var $ = jQuery = require('jquery');
	var noSelect = require('noSelect');
	var browser = require("browser")();
	require('grid/form-grid.css');

	function Grid($elem, options) {

		var defaultOptions = {
			url : '',
			width : '100%',
			height : '',
			header : [],
			data : [],
			pageSize : 10
		};
		options = jQuery.extend({}, defaultOptions, options);
		if (!$elem || !($elem instanceof jQuery) || $elem.length !== 1) {
			throw new Error('Invalid parameter for jquery.grid.');
		}
		this.options = options;
		this.el = $elem;
		var self = this;
		if (options.url != '') {
			this.ajax = true;
		} else {
			this.ajax = false;
		}
		if ($('.grid-split-line').size() == 0) {
			$('body').append($('<div/>').addClass("grid-split-line"));
		}
		var resizeLine = $($('.grid-split-line').get(0));
		this.resizeLine = resizeLine;
		// grid-overlay
		if ($('.grid-overlay').size() == 0) {
			$elem.append($('<div><span>&nbsp;</span></div>').addClass("grid-overlay").hide());
		}
		var overLay = $($('.grid-overlay').get(0));
		this.overLay = overLay;
		$elem.css("width", options.width + "px");
		$elem.addClass('grid-div');

		this.headInfo = this.options.header;

		this.initGrid();

		this.pageIndex = 1;
		this.pageSizeSelect.val(this.options.pageSize);

		this.bindFooterEvent();
		if (this.ajax) {
			this.loadData();
		} else {
			var tp = this.countTotalPage(this.options.data.length, this.options.pageSize);
			this.totalPageSpan.text(tp);
			this.totalCountSpan.text(this.options.data.length);
			this.loadLocalData();
		}

	}

	Grid.prototype.getSelectRecord = function() {
		
		var ret = {};
		var cked = $('.grid-div-body-table-value input[type="checkbox"], .grid-div-body-table-value input[type="radio"]');
		var head = $('.grid-div-header-title input[type="checkbox"], .grid-div-header-title input[type="radio"]');
		if(head) {
			head.each(function(){
				ret.name = $(this).attr('columnName');
			});
		}
		var values = [];
		if (cked) {
			for ( var i = 0; i < cked.size(); i++) {
				if (cked.get(i).checked) {
					values.push(cked.get(i).value);
				}
			}
		}

		ret.value = values;
		return ret;
	};

	Grid.prototype.countTotalPage = function(count, pageSize) {
		var tp = parseInt(count / pageSize);
		if (count % pageSize != 0) {
			tp++;
		}
		return tp;
	};

	Grid.prototype.loadLocalData = function() {
		this.createTr(this.getLocalPageData());
	};

	Grid.prototype.getLocalPageData = function() {
		this.startLoad();
		var pageSize = this.getPageSize();
		var start = (this.getPageIndex() - 1) * pageSize;// 1=>0 2=>10
		var end = this.getPageIndex() * pageSize - 1;// 1=9 2=>19
		if (end > this.options.data.length - 1) {
			end = this.options.data.length - 1;
		}
		var arr = [];
		for ( var i = start; i <= end; i++) {
			arr.push(this.options.data[i]);
		}
		return arr;
	};

	Grid.prototype.loadData = function() {
		this.startLoad();
		var self = this;
		if (this.ajax) {
			$.post(this.options.url, {
				pageSize : this.pageSizeSelect.val(),
				pageIndex : this.pageIndexInput.val(),
				timestamp : new Date().getTime()
			}, function(data) {
				// total page ? & total records
				var pageSize = self.getPageSize();
				var tp = self.countTotalPage(data.count, pageSize);
				self.totalPageSpan.text(tp);
				self.totalCountSpan.text(data.count);
				self.createTr(data.data);
			}, "json");
		} else {
			this.loadLocalData();
		}
	};

	Grid.prototype.bindFooterEvent = function() {
		var self = this;
		this.prevBtn.bind('click', function() {
			if (self.getPageIndex() == 1) {
				return;
			}
			self.setPageIndex(self.getPageIndex() - 1);
			self.loadData();
		});
		this.firstBtn.bind('click', function() {
			if (self.getPageIndex() == 1) {
				return;
			}
			self.setPageIndex(1);
			self.loadData();
		});
		this.nextBtn.bind('click', function() {
			if (self.getPageIndex() >= self.getTotalPage()) {
				return;
			}
			self.setPageIndex(self.getPageIndex() + 1);
			self.loadData();
		});
		this.lastBtn.bind('click', function() {
			if (self.getPageIndex() >= self.getTotalPage()) {
				return;
			}
			// self.totalPageSpan
			self.setPageIndex(self.getTotalPage());
			self.loadData();
		});
		this.pageSizeSelect.change(function() {
			self.setPageSize(this.value);
			self.setPageIndex(1);
			if (!self.ajax) {
				var tp = self.countTotalPage(self.options.data.length, this.value);
				self.totalPageSpan.text(tp);
			}
			self.loadData();
		});
		this.refreshBtnSpan.bind('click', function() {
			self.loadData();
		});
		this.pageIndexInput.change(function() {
			if (this.value == '') {
				this.value = self._pageIndex;
				return;
			}
			var v = parseInt(this.value);
			if (isNaN(v)) {
				this.value = self._pageIndex;
				return;
			}
			if (v > self.getTotalPage() || v < 1) {
				this.value = self._pageIndex;
				return;
			}
			self.setPageIndex(v);
			self.loadData();
		});
	};

	Grid.prototype.getPageSize = function() {
		return parseInt(this.pageSizeSelect.val());
	};
	Grid.prototype.getPageIndex = function() {
		return parseInt(this.pageIndexInput.val());
	};
	Grid.prototype.getTotalPage = function() {
		return parseInt(this.totalPageSpan.text());
	};
	Grid.prototype.setPageSize = function(pageSize) {
		return this.pageSizeSelect.val(pageSize);
	};
	Grid.prototype.setPageIndex = function(pageIndex) {
		this._pageIndex = pageIndex;
		return this.pageIndexInput.val(pageIndex);
	};

	// Grid.prototype.create
	Grid.prototype.createHeader = function() {
		var headerDivBk = $('<div/>').addClass("grid-div-header-bk");
		var headerDiv = $('<div/>').addClass("grid-div-header");
		var headerTable = $('<table>').addClass("grid-div-header-table");
		var headerTr = $('<tr align="center"></tr>');
		for ( var i = 0; i < this.headInfo.length; i++) {
			var op = this.headInfo[i];
			var title = op.title;

			var hd = $("<div/>").addClass("grid-div-header-title").css("width", op.width + "px")

			if (op.type == 'checkbox') {
				var vname = op.name;
				var ck = $("<input type='checkbox' columnName='"+vname+"' name='head_" + vname + "'>").bind('click', function() {
					var many = $('.grid-div-body-table  input[type=checkbox][name="' + vname + '"]');
					for ( var k = 0; k < many.length; k++) {
						many.get(k).checked = this.checked;
					}
				});
				$(hd).html(ck);
			} else {
				$(hd).html(title);
			}

			var td = $('<td></td>');
			td.append(hd);

			headerTr.append(td);
		}
		headerTable.append(headerTr);
		headerDiv.append(headerTable);
		headerDivBk.append(headerDiv);
		this.el.append(headerDivBk);
	};

	Grid.prototype.createBody = function() {
		var body = $('<div>').addClass('grid-div-body');
		var table = $('<table>').addClass('grid-div-body-table');
		// var length = this.options.pageSize;
		for ( var i = 0; i < this.options.pageSize; i++) {
			var tr = $('<tr>');
			if (i % 2 != 0) {
				tr.addClass('grid-div-body-table-old');
			}
			for ( var j = 0; j < this.options.header.length; j++) {
				var td = $('<td>');
				var valueDiv = $('<div>').addClass("grid-div-body-table-value");
				valueDiv.html("&nbsp;");
				td.append(valueDiv);
				tr.append(td);
			}
			table.append(tr);
		}
		body.append(table);
		this.el.append(body);
	};

	Grid.prototype.createFooter = function() {
		var footer = $('<div/>').addClass('grid-div-footer');
		var fpage = $('<div/>').addClass('grid-div-footer-page');

		fpage.append($('<span/>').addClass('grid-div-footer-first').append($('<span class="grid-div-footer-page-blank-span">&nbsp;</span>')));
		fpage.append($('<span/>').addClass('grid-div-footer-prev').append($('<span class="grid-div-footer-page-blank-span">&nbsp;</span>')));
		fpage.append($('<span class="grid-div-footer-split-span">&nbsp;</span>'));

		fpage.append($('<span>').append(
				'第<input type="text" class="grid-div-footer-page-input" value="1">页/共<span class="total-page"></span>页(<span class="total-count">24</span>条记录)'));
		fpage.append($('<span class="grid-div-footer-split-span">&nbsp;</span>'));

		fpage.append($('<span/>').addClass('grid-div-footer-next').append($('<span class="grid-div-footer-page-blank-span">&nbsp;</span>')));
		fpage.append($('<span/>').addClass('grid-div-footer-last').append($('<span class="grid-div-footer-page-blank-span">&nbsp;</span>')));

		fpage.append($('<span class="grid-div-footer-split-span">&nbsp;</span>'));
		fpage.append($('<span class="grid-div-footer-refresh"><span class="grid-div-footer-page-blank-span">&nbsp;</span></span>'));
		footer.append(fpage);
		// grid-div-footer-page-size
		footer
				.append($('<div/>')
						.addClass('grid-div-footer-count')
						.append(
								$('<span>每页记录数:<select class="grid-div-footer-page-size"><option value="10">10</option><option value="20">20</option><option value="30">30</option><option value="40">40</option><option value="50">50</option><option value="100">100</option></select></span>')));

		this.el.append(footer);
	};

	Grid.prototype.startLoad = function() {
		// this.refreshBtnSpan.addClass("grid-div-footer-loading");
		var p = this.bodyDiv.offset();
		this.overLay.css({
			top : p.top,
			left : p.left
		}).height(this.bodyDiv.height()).width(this.bodyDiv.width()).show();
	};

	Grid.prototype.afterLoad = function() {
		this.overLay.fadeOut(100);
		// this.refreshBtnSpan.removeClass("grid-div-footer-loading");
	};

	Grid.prototype.createTr = function(dataArray) {
		var t = this.table;
		t.empty();
		var header = this.headInfo;
		for ( var i = 0; i < dataArray.length; i++) {
			var d = dataArray[i];
			var tr = $('<tr>');
			var isLastRow = (i == dataArray.length - 1);
			if (isLastRow) {
				// last row
				tr.css("border-bottom", "0");
			}
			if (i % 2 != 0) {
				tr.addClass('grid-div-body-table-old');
			}
			for ( var j = 0; j < d.length; j++) {
				var r = d[j];
				var td = $('<td>');
				if (isLastRow) {
					// last row
					td.css("border-bottom", "0");
				}
				if (j == d.length - 1) {
					// last cell
					td.css("border-right", "0");
				}
				var valueDiv = $('<div>').addClass("grid-div-body-table-value");

				var vtype = header[j].type;
				if (vtype == 'columnText') {
					valueDiv.html("<div name='" + header[j].name + "'>" + r + "</div>");
				} else if (vtype == 'checkbox') {
					var vname = header[j].name;
					var ck = $("<input type='checkbox' name='" + header[j].name + "' value='" + r + "'>").bind('click', function() {
						var many = $('.grid-div-body-table  input[type=checkbox][name="' + vname + '"]');
						var all = true;
						for ( var k = 0; k < many.length; k++) {
							if (!many.get(k).checked) {
								all = false;
							}
						}
						$('.grid-div-header-table input[type=checkbox][name="head_' + vname + '"]').get(0).checked = all;
					});
					valueDiv.append(ck);
					td.attr("align", "center");
				} else if (vtype == 'radio') {
					valueDiv.html("<input type='radio' name='" + header[j].name + "' value='" + r + "'>");
					td.attr("align", "center");
				} else if (vtype == 'link') {

				} else {
					valueDiv.html("<div name='" + header[j].name + "'>" + r + "</div>");
				}

				td.append(valueDiv);
				tr.append(td);
			}
			t.append(tr);
		}
		this.synWidth();
		this.bindResizeEvent();
		this.bindScrollEvent();
		this.afterLoad();
	};

	Grid.prototype.synWidth = function() {
		var tr = this.table.find("tr")[0];
		var tdArray = $(tr).find("td");
		var columns = this.headTable.find("td");
		for ( var i = 0; i < columns.length; i++) {
			var d = $(columns[i]).find("div");
			$($(tdArray[i]).find("div")).width($(d).width());
		}
	};
	Grid.prototype.bindScrollEvent = function() {
		var self = this;
		this.bodyDiv.scroll(function() {
			self.headDiv.scrollLeft($(this).scrollLeft());
		});
	};
	Grid.prototype.bindResizeEvent = function() {
		var tds = this.headTable.find('td');
		tds.bind("mousemove", function(event) {
			var th = $(this);
			var pos = th.offset();
			if (event.clientX - pos.left < 4 || (th.width() - (event.clientX - pos.left)) < 4) {
				th.css({
					'cursor' : 'e-resize'
				});
			} else {
				th.css({
					'cursor' : 'default'
				});
			}
		});
		var self = this;
		tds.bind("mousedown", function(event) {
			var th = $(this);
			var pos = th.offset();
			if (event.clientX - pos.left < th.width() / 2) {
				self.cruut = th.prev();
			} else {
				self.cruut = th;
			}

			noSelect($('body'));

			if (event.clientX - pos.left < 4 || (th.width() - (event.clientX - pos.left)) < 4) {
				var height = self.bodyDiv.height() + self.headTable.height();
				var top = pos.top;
				self.resizeLine.css({
					"height" : height,
					"top" : top,
					"left" : event.clientX,
					"display" : ""
				});
				self.lineMove = true;
				$("body").bind("mousemove", function(event) {
					if (self.lineMove == true) {
						var left1 = self.bodyDiv.offset().left;
						var left2 = left1 + self.bodyDiv.width();
						if (event.clientX < left1 || event.clientX > left2) {
							self.resizeLine.css({
								"left" : event.clientX
							}).hide();
						} else {
							self.resizeLine.css({
								"left" : event.clientX
							}).show();
						}
					}
				});
				$("body").bind("mouseup", function(event) {
					if (self.lineMove == true) {
						self.resizeLine.hide();
						self.lineMove = false;
						var pos = self.cruut.offset();
						var index = self.cruut.prevAll().length;
						self.cruut.width(event.clientX - pos.left);
						self.cruut.parent().parent().find("tr").each(function() {
							$(this).children().eq(index).find("div").width(event.clientX - pos.left);
						});
						self.synWidth();
					}
					// $('body').noSelect(false);
					noSelect($('body'), false);
				});
			}
		});
	};

	Grid.prototype.initGrid = function() {
		this.createHeader();
		this.createBody();
		this.createFooter();
		$elem = this.el;
		this.table = $elem.find('.grid-div-body-table');
		this.bodyDiv = $elem.find('.grid-div-body');
		// TODO
		if (this.options.width == '') {

		} else {
			this.bodyDiv.css("width", this.options.width);
		}
		this.headDiv = $($elem.find('.grid-div-header').get(0));
		this.headDiv.width(this.bodyDiv.width() - 17);

		this.headTable = $elem.find('.grid-div-header-table');
		this.footerDiv = $($elem.find('.grid-div-footer').get(0));

		// height should auto
		if (this.options.height == '') {
			var autoHeight = $(window).height() - this.headDiv.offset().top - this.headDiv.outerHeight() - this.footerDiv.outerHeight() - 10;
			if (browser.msie) {
				//autoHeight = autoHeight - 100;
			}
			$(this.bodyDiv.get(0)).css("height", (autoHeight) + "px");
		} else {
			$(this.bodyDiv.get(0)).css("height", this.options.height);
		}

		var pageIndexInput = $(this.footerDiv.find('.grid-div-footer-page-input').get(0));
		var totalPageSpan = $(this.footerDiv.find('.total-page').get(0));
		var totalCountSpan = $(this.footerDiv.find('.total-count').get(0));
		var pageSizeSelect = $(this.footerDiv.find('.grid-div-footer-page-size').get(0));
		var firstBtn = $(this.footerDiv.find('.grid-div-footer-first').get(0));
		var prevBtn = $(this.footerDiv.find('.grid-div-footer-prev').get(0));
		var nextBtn = $(this.footerDiv.find('.grid-div-footer-next').get(0));
		var lastBtn = $(this.footerDiv.find('.grid-div-footer-last').get(0));
		var refreshBtn = $(this.footerDiv.find('.grid-div-footer-refresh').get(0));
		this.pageIndexInput = pageIndexInput;
		this.totalPageSpan = totalPageSpan;
		this.totalCountSpan = totalCountSpan;
		this.pageSizeSelect = pageSizeSelect;
		this.refreshBtnSpan = refreshBtn;
		this.firstBtn = firstBtn;
		this.prevBtn = prevBtn;
		this.nextBtn = nextBtn;
		this.lastBtn = lastBtn;
	};

	return function(ele, opt) {
		return new Grid(ele, opt);
	}
});